/*
 * For legal stuff see the file COPYRIGHT
 */
#import <stdio.h>
#import <stdlib.h>
#import "Expense.h"

extern void freeAndCopy( char **ptr, const char *str );
extern char *NXCopyStringBuffer(const char *buffer);

@implementation Expense

- init:(const char *)date
       description:(const char *)desc
       amount:(const float)amt
{
  [self setDateString:date];
  [self setDescription:desc];
  amount = amt;
  return self;
}

- (void) freeDesc
{
  if ( description ) {
    free( description );
    description = NULL;
  }
}

- free
{
  [self freeDesc];
  return [super free];
}

- setAmount:(float)value
{
  amount = value;
  return self;
}

- setDateString:(const char *)str
{
  freeAndCopy( &dateString, str );
  return self;
}

- setDescription:(const char *)desc
{
  [self freeDesc];
  description = NXCopyStringBuffer(desc);
  return self;
}

- (const char *)dateString
{
  return dateString;
}

- (const char *)description
{
  return description;
}

- (float)amount
{
  return amount;
}

/*
 * For use in comparisons, convert date such as 11/21/93 to a
 * single integer 932111. THIS SHOULD BE CACHED! (TBD)
 */
- (int)dateValue
{
  int day, month, year;

  sscanf( dateString, "%d/%d/%d", &month, &day, &year );
  return ( year * 10000 + month * 100 + day );
}

- read:(NXTypedStream *) stream
{
  NXReadTypes( stream, "**f", &description, &dateString, &amount );
  return self;
}

- write:(NXTypedStream *) stream
{
  NXWriteTypes( stream, "**f", &description, &dateString, &amount );
  return self;
}

@end
